package fragment;

import java.util.List;
import java.util.Random;

import com.example.googlemarketdemo.R;

import protocol.HotProtocol;

import base.BaseFragment;
import base.LoadingPager.LoadResult;
import utils.UIUtils;
import view.FlowLayout;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;

import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class HotFragment extends BaseFragment {
	
	private List<String> mDatas;

	/**
	 * 
	 */
	@Override
	protected LoadResult initData() {
		SystemClock.sleep(2000);
		//成功
		//失败
		//错误
		HotProtocol protocol =  new HotProtocol();
		
		try {
			mDatas = protocol.loadData(0);
			return checkState(mDatas);
		} catch (Exception e) {
			e.printStackTrace();
			return LoadResult.ERROR;
		}
	}

	@Override
	protected View initSuccessView() {
		//流式布局
		ScrollView sv = new ScrollView(UIUtils.getContext());
		 FlowLayout fl = new FlowLayout(UIUtils.getContext());
		 
		 for (final String info:mDatas) {
			TextView tv = new TextView(UIUtils.getContext());
			//设置文本的内容
			tv.setText(info);
			int padding = UIUtils.dip2px(5);
			tv.setPadding(padding, padding, padding, padding);
			tv.setGravity(Gravity.CENTER);
			//设置圆角背景
			tv.setBackgroundResource(R.drawable.shape_hot_tv);
			tv.setTextColor(Color.WHITE);
			GradientDrawable normalBg = new GradientDrawable();
			normalBg.setCornerRadius(10);
			
			//设置随机颜色
			Random random =new Random();
			int alpha =255;
			int red = random.nextInt(170)+30;//0-255
			int green = random.nextInt(170)+30;
			int blue = random.nextInt(170)+30;
			int argb =  Color.argb(alpha, red, green, blue);
			normalBg.setColor(argb);
			
			//按下效果
			GradientDrawable pressBg = new GradientDrawable();
			pressBg.setCornerRadius(10);
			pressBg.setColor(Color.DKGRAY);//设置为深灰色
			
			StateListDrawable selectorBg  = new StateListDrawable();
		
			selectorBg.addState(new int[]{android.R.attr.state_pressed}, pressBg);//按下的状态
			selectorBg.addState(new int[]{}, normalBg);//默认状态
			tv.setBackgroundDrawable(selectorBg);
			tv.setClickable(true);	
			
			tv.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Toast.makeText(UIUtils.getContext(),info, 0).show();
					
				}
			});
			
			fl.addView(tv);
		}
		 
		 
		 sv.addView(fl);
		return sv;
	}

}
